<template>
  <div class="page-box">
    <div class="fix-pos">
      <el-button type="warning"
                 size="mini"
                 icon="el-icon-refresh"
                 @click="initData"
                 plain>刷新</el-button>
      <!-- <el-button type="primary"
                 size="mini"
                 icon="el-icon-plus"
                 plain
                 @click="$refs.info.isShow=true">增加</el-button> -->
    </div>
    <el-form label-width="200px"
             ref="form"
             :model="configForm"
             :rules="configRules">
      <el-tabs v-model="activeName">
        <el-tab-pane :name="item.key"
                     :label="item.name"
                     v-for="(item,index) in list"
                     :key="index">
          <!-- 内容模板 -->
          <el-card :body-style="{ padding: '20px' }">
            <div v-for="(row,key) in item.children"
                    :key="key">
              <el-divider direction="horizontal"
                          content-position="left">
                <h3>{{row.name}}</h3>
              </el-divider>
              <el-row  v-for="(val,idx) in row.data" :key="idx">
                <el-col :span="16" :offset="2" >
                  <el-form-item :label="val.attr_name"
                                size="normal"
                                :prop="val.attr_key">
                    <!-- 展示不同的控件 -->
                    <!-- 1 是单行 -->
                    <template v-if="val.type===1">
                      <el-input v-model="configForm[val.attr_key]"
                                :placeholder="val.placeholder"
                                size="normal"
                                clearable></el-input>
                    </template>
                    <!-- 2是密码 -->
                    <template v-else-if="val.type===2">
                      <el-input type="password"
                                v-model="configForm[val.attr_key]"
                                :placeholder="val.placeholder"
                                size="normal"
                                clearable
                                show-password></el-input>
                    </template>
                    <!-- 3是 多行文本 -->
                    <template v-else-if="val.type===3">
                      <el-input type="textarea"
                                rows="4"
                                v-model="configForm[val.attr_key]"
                                :placeholder="val.placeholder"
                                size="normal"
                                clearable></el-input>
                    </template>
                    <!-- 4是 下拉框/单选框 -->
                    <template v-else-if="val.type===4">
                      <el-select v-model="configForm[val.attr_key]"
                                :placeholder="val.placeholder"
                                clearable  >
                        <el-option v-for="item in val.config_value"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value">
                        </el-option>
                      </el-select>
                    </template>
                    <!-- 5 是 多选下拉框/多选框 -->
                    <template v-else-if="val.type===5">
                      <el-select v-model="configForm[val.attr_key]"
                                :placeholder="val.placeholder"
                                multiple
                                clearable  >
                        <el-option v-for="item in val.config_value"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value">
                        </el-option>
                      </el-select>
                    </template>
                    <!-- 6是时间选择器 -->
                    <template v-else-if="val.type===6">
                      <el-time-picker v-model="configForm[val.attr_key]"
                                      :placeholder="val.placeholder"></el-time-picker>
                    </template>
                    <!-- 7 日期选择器 -->
                    <template v-else-if="val.type===7">
                      <el-date-picker type="date"
                                      v-model="configForm[val.attr_key]"
                                      :placeholder="val.placeholder"></el-date-picker>
                    </template>
                    <!-- 8 时间日期选择器 -->
                    <template v-else-if="val.type===8">
                      <el-date-picker type="datetime"
                                      :value="'Thu Oct 22 2020 00:00:00 GMT+0800 (中国标准时间)'"
                                      :placeholder="val.placeholder"></el-date-picker>
                    </template>
                    <!-- 9 图片上传控件 -->
                    <template v-else-if="val.type===9">
                      <image-upload :limit="1" v-model="configForm[val.attr_key]" field-name="file" :upload-fn="uploadFile" />
                      <p style="color:#555;font-size:12px;">{{val.placeholder}}</p>
                    </template>
                  </el-form-item>
                </el-col>
                <el-col :span="2" :offset="4">
                  <el-button v-if="val.can_delete*1===1" type="danger" @click="del(val.id)" plain size="small" circle icon="el-icon-delete"></el-button>
                </el-col>
              </el-row>
            </div>
            <div>
              <el-divider class="clearfix"
                          direction="horizontal"></el-divider>
              <el-col :span="16"  :offset="2">
                <el-form-item>
                  <el-button type="primary"
                             @click="save" size="small">保存</el-button>
                  <el-button @click="reset" size="small">重置</el-button>
                </el-form-item>
              </el-col>
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <!-- 弹框 -->
    <v-info ref="info" @update="initData" :list="list"></v-info>
  </div>
</template>
<script>
import VInfo from './components/info'
import { mapGetters } from 'vuex'
import { getConfig, saveConfig, delConfig } from '@/api/system/config'
import { tabValue } from '@/api/constant/config'
import { uploadFile } from '@/api/index'
export default {
  name: 'Config',
  data () {
    return {
      activeName: tabValue[0].key,
      configForm: {},
      configRules: {},
      list: [],
      allData: []
    }
  },
  computed: {
    ...mapGetters(['token'])
  },
  mounted () {
    this.initData()
  },
  methods: {
    uploadFile,
    // 获取列表
    async initData () {
      const { list, configForm, configRules, allData } = await getConfig()
      const keys = Object.keys(configRules)
      // 处理验证规则JSON字符串问题
      keys.forEach(key => {
        try {
          configRules[key] = JSON.parse(configRules[key])
        } catch (error) {
          configRules[key] = []
        }
      })
      // 处理图片路径转字符串问题
      allData.forEach(item => {
        if (item.type * 1 === 9) {
          configForm[item.attr_key] = configForm[item.attr_key] ? [configForm[item.attr_key]] : []
        }
      })
      this.list = list
      this.allData = allData
      this.configForm = configForm
      this.configRules = configRules
    },
    save () {
      this.$refs.form.validate(async valid => {
        if (!valid) return this.$message.warning('验证不通过')
        const configFormClone = JSON.parse(JSON.stringify(this.configForm))
        const attrKey = Object.keys(configFormClone)
        const data = attrKey.map(key => {
          const row = this.allData.find(item => item.attr_key === key)
          return {
            id: row.id,
            attr_key: key,
            // 处理图片
            attr_value: row.type * 1 === 9 ? configFormClone[key].join() : configFormClone[key]
          }
        })
        await saveConfig(data)
        // 重新加载配置
        this.$store.dispatch('settings/loadConfig')
        this.$message.success('保存成功')
      })
    },
    reset () {
      this.$refs.form.resetFields()
    },
    // 删除
    async del (id) {
      try {
        await this.$confirm('确定删除吗？')
        await delConfig(id)
        this.$message.success('删除成功')
        this.initData()
      } catch (error) {
        console.log(error)
      }
    }
  },
  components: {
    VInfo
  }
}
</script>
<style scoped>
.page-box{
  position: relative;
}
.fix-pos{
    position: absolute;
    right: 30px;
    top: 20px;
    z-index: 10;
}
</style>
